/**
 * 高德POI 查询栏 （左上角）
 * @copyright 火星科技 mars2d.cn
 * @author 火星吴彦祖 2022-01-10
 */

import * as mars2d from "mars2d"
import "leaflet-plugin-trackplayback/dist/leaflet.trackplayback"
import "leaflet-plugin-trackplayback/dist/control.playback.css"
import "leaflet-plugin-trackplayback/dist/control.trackplayback"
import { AntPath, antPath } from "leaflet-ant-path"

import { GetTraceList, GetShipPositions, GetShipPositionsByDay } from "@mars/common/api/modules/trace"
import { graphic } from "echarts"

const L = mars2d.L

let map: mars2d.Map // 地图对象
let graphicLayer: mars2d.layer.GraphicLayer // 船舶位置
let graphicLayer1: mars2d.layer.GraphicLayer // 历史轨迹

export const eventTarget = new mars2d.BaseClass()

// 初始化当前业务
export function onMounted(mapInstance: mars2d.Map): void {
  map = mapInstance // 记录map

  graphicLayer = new mars2d.layer.GraphicLayer({
    name: "船舶位置",
    pid: 99, // 图层管理 中使用，父节点id,
    show: true
  })
  graphicLayer1 = new mars2d.layer.GraphicLayer({
    name: "历史轨迹",
    pid: 99, // 图层管理 中使用，父节点id,
    show: true
  })
  map.addLayer(graphicLayer)
  map.addLayer(graphicLayer1)

  graphicLayer.bindPopup(function (event: any) {
    const item = event.attr
    if (!item) {
      return
    }
    console.log(item)
    let inHtml = `<div class="mars2d-template-titile"><a target="_black" style="color: #ffffff; ">${item.Name}</a></div><div class="mars2d-template-content" >`

    if (item.Name && item.Name !== "") {
      inHtml += "<div><label>航速:</label>" + item.Speed + "</div>"
    }
    if (item.Name) {
      inHtml += "<div><label>时间:</label>" + item.Time + "</div>"
      inHtml += `<div><label>位置:</label>${item.Lon},${item.Lat}</div>`
    }
    inHtml += '<div><button id="btnDetails" style="width:100px;height:30px;">查看轨迹</button></div>'
    inHtml += "</div>"
    return inHtml
  })
  graphicLayer.on(mars2d.EventType.popupopen, function (event) {
    const container = event.popup._container // popup对应的DOM
    console.log("打开了popup", container)
    const btnDetails = container.querySelector("#btnDetails")
    if (btnDetails) {
      btnDetails.addEventListener("click", (e) => {
        console.log(event.sourceTarget.id)
        showHistoryPositions(event.sourceTarget.id)
        // var showHistoryLayer = true
        // eventTarget.fire('showWebsite', { showHistoryLayer })
      })
    }
  })
}

// 查询数据 //"2023-02-02 01:00:00"
export function updateShipPositions(time: string): void {
  GetShipPositions({
    time: time
  }).then((res) => {
    if (res.ResultType === "Success") {
      console.log(res.Data)
      for (let index = 0; index < res.Data.length; index++) {
        const element = res.Data[index]
        const point = [element.Lat, element.Lon]
        const pointEntity = new mars2d.graphic.Point({
          id: element.Name,
          latlng: point,
          style: {
            pixelSize: 3,
            color: "yellow"
          },
          attr: element
        })
        graphicLayer.addGraphic(pointEntity)
      }
    } else {
      // $message(res.msg)
    }
  })
}
export function showHistoryPositions(name: string) {
  GetTraceList({
    name: name
  }).then((res) => {
    if (res.ResultType === "Success") {
      console.log(res.Data)
      const latlngs = []
      graphicLayer1.clear()
      for (let index = 0; index < res.Data.length; index++) {
        const element = res.Data[index]
        const point = [element.Lat, element.Lon]
        latlngs.push(point)
        const pointEntity = new mars2d.graphic.Point({
          // id: element.Name,
          latlng: point,
          style: {
            pixelSize: 2,
            color: "green"
          },
          attr: element
        })
        graphicLayer1.addGraphic(pointEntity)
      }

      // 预测路线
      const options = { use: L.polyline, delay: 800, dashArray: [10, 20], weight: 5, color: "#0000FF", pulseColor: "#FFFFFF" }
      const graphicLine = antPath(latlngs, options)
      graphicLine.addTo(graphicLayer1)
      graphicLayer1.flyTo()
      // 在图层上绘画出所有的点
    } else {
      // $message(res.msg)
    }
  })
}

export function flyTo(name: string) {
  const graphic = graphicLayer.getGraphicById(name)
  graphicLayer.openPopup(graphic)
  map.flyToGraphic(graphic)
}

// 释放当前业务
export function onUnmounted(): void {
  map.removeLayer(graphicLayer)
  graphicLayer.remove()
  map.removeLayer(graphicLayer1)
  graphicLayer1.remove()

  map = null
}

/**
 * 加载查询之后的数据，通过矢量数据展示出来
 * @param {any} arr 查询之后的数据
 * @returns {void} 无
 */
export function showPOIArr(arr: any): void {
  clearLayers()
  arr.forEach((item: any) => {
    const jd = Number(item.lng)
    const wd = Number(item.lat)
    if (isNaN(jd) || isNaN(wd)) {
      return
    }

    item.lng = jd
    item.lat = wd

    // 添加实体
    const graphic = new mars2d.graphic.Marker({
      latlng: [wd, jd],
      style: {
        image: "img/marker/mark1.png",
        width: 32,
        height: 44,
        horizontalOrigin: mars2d.HorizontalOrigin.CENTER,
        verticalOrigin: mars2d.VerticalOrigin.BOTTOM
        // label: {
        //   text: item.name,
        //   font_size: 20,
        //   color: "rgb(240,255,255)",
        //   outline: true,
        //   outlineWidth: 2,
        //   pixelOffsetY: -10, //偏移量
        // },
      },
      attr: item
    })
    graphicLayer.addGraphic(graphic)
    item._graphic = graphic
  })

  if (arr.length > 1) {
    graphicLayer.flyTo()
  }
}

/**
 * 判断是否为经纬度值，
 * 若是，加载为矢量数据且定位至该矢量数据
 * 若否，返回
 * @param {string} text 输入框输入的关键字
 * @returns {void} 无
 */
export function centerAtLonLat(text: string): void {
  const arr = text.split(",")
  if (arr.length !== 2) {
    return
  }

  const jd = Number(arr[0])
  const wd = Number(arr[1])
  if (isNaN(jd) || isNaN(wd)) {
    return
  }

  // 添加实体
  const graphic = new mars2d.graphic.Marker({
    latlng: [wd, jd],
    style: {
      image: "img/marker/mark1.png",
      width: 32,
      height: 44,
      horizontalOrigin: mars2d.HorizontalOrigin.CENTER,
      verticalOrigin: mars2d.VerticalOrigin.BOTTOM
    }
  })
  graphicLayer.addGraphic(graphic)

  graphic.bindPopup(`<div class="mars2d-template-titile">坐标定位</div>
              <div class="mars2d-template-content" >
                <div><label>经度</label> ${jd}</div>
                <div><label>纬度</label>${wd}</div>
              </div>`)

  map.flyToGraphic(graphic)
  graphicLayer.openPopup(graphic)
}

export function flyToGraphic(graphic: any, option: any): void {
  graphicLayer.openPopup(graphic)
  map.flyToGraphic(graphic, option)
}

export function clearLayers(): void {
  graphicLayer.closePopup()
  graphicLayer.clear()
}

export function testPlugins(params: string) {
  // const trackplayback1 = mars2d.L.trackPlayBack(null, map, {
  //   targetOptions: {
  //     useImg: true,
  //     imgUrl: "./ship.png"
  //   }
  // })
  // const trackplaybackControl1 = mars2d.L.trackplaybackcontrol(trackplayback1)
  // trackplaybackControl1.addTo(map)
}
